package com.heima.user.service.impl;

import com.heima.common.exception.CustException;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer authorApUserId = dto.getAuthorApUserId();
        Short operation = dto.getOperation();
        if (operation==null || (operation.intValue() != 0 && operation.intValue() !=1)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        ZSetOperations<String, String> zsetOperation = redisTemplate.opsForZSet();
        if (operation==0) {
            if (user.getId().equals(authorApUserId)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"不能关注自己");
            }
            Double score = zsetOperation.score(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(authorApUserId));
            if (score!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"不能重复关注");
            }
            //      follow:loginId   作者id     添加数据
            zsetOperation.add(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(authorApUserId), System.currentTimeMillis());
            //     fans : 作者id      loginId   添加数据
            zsetOperation.add(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(user.getId()), System.currentTimeMillis());
        } else {
            //      follow:loginId   作者id     删除数据
            zsetOperation.remove(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(authorApUserId));
            //     fans : 作者id      loginId   删除数据
            zsetOperation.remove(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(user.getId()));
        }
        return null;
    }
}
